<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.js"></script>
<div id="blobPictureManager">
    <div id="managerContainer">
        <h1>Picture Upload Manager</h1>
        <div id="directoryTree">
            <div class="content"></div>
        </div>
        <div id="fileInfo">
            <div class="content">No file selected.</div>
        </div>
        <div id="managerActions">
            <form><input type="file" name="imageUpload" id="imageUpload" /></form>
            <input type="button" id="btnHomeContainer" class="btn btn-container disabled" title="Top Container" />
            <input type="button" id="btnRefresh" class="btn btn-refresh disabled" title="Refresh" />
            <div class="seperator"></div>
            <input type="button" id="btnParentDirectory" class="btn btn-parent disabled" title="Go to Parent Folder" />
            <input type="button" id="btnNewDirectory" class="btn btn-newdir" title="Create Folder" />
            <input type="button" id="btnRemoveDirectory" class="btn btn-removedir disabled" title="Delete Folder" />
            <div class="seperator"></div>
            <input type="button" id="btnUploadImage" class="btn btn-upload" title="Upload Image" />
            <input type="button" id="btnDownloadImage" class="btn btn-download disabled" title="Download Image" />
            <input type="button" id="btnRemoveImage" class="btn btn-remove disabled" title="Delete Image" />
        </div>
        <div id="folderContent">
            <div class="content"></div>
            <div class="folder-background"></div>
        </div>
    </div>
    <div id="savedFolderContent"></div>
</div>
<style>
    html, body, .master-wrapper-page, .master-wrapper-content {
        height: 100%;
    }
    .master-wrapper-content > .content {
        position: absolute;
        top: 130px;
        bottom: 0;
        width: 100%;
        min-width: 960px;
    }
    .master-wrapper-content > .content > .cph {
        height: 100%;
        padding: 0;
        min-width: 960px;
    }
    body {
        min-width: 960px;
    }
    
    #blobPictureManager {
        position: relative;
        height: 100%;
        width: 100%;
        background: #eee;
    }
    #blobPictureManager h1 {
        padding: 10px 15px;
        border-bottom: 1px solid #ddd;
        background: #eee;
        position: relative;
        z-index: 10;
    }
    #savedFolderContent {
        display: none;
    }
    #directoryTree {
        background: #fff;
        position: absolute;
        top: 0;
        left: 0;
        width:0;
        height: 100%;
    }
    #fileInfo {
        background: #55A7FF;
        position: absolute;
        top: 0;
        right: 0;
        width:25%;
        height: 100%;
        padding-top: 50px;
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        overflow: auto;
    }
    #fileInfo .content {
        margin: 25px;
        color: #fff;
        text-align: center;
    }
    #fileInfo .fileinfo-icon .fileicon {
        margin: auto;
    }
    #fileInfo .fileinfo-name {
        font-weight: bold;
    }
    #fileInfo .fileinfo-thumb img {
        max-width: 100%;
        max-height: 300px;
    }
    #fileInfo .fileinfo-icon, #fileInfo .fileinfo-thumb, #fileInfo .fileinfo-name {
        margin-bottom: 10px;
    }
    #fileInfo .fileinfo-url {
        margin: 15px 0;
    }
    #fileInfo .fileinfo-url a {
        color: #0c519c;
        -ms-word-break: break-all;
        word-break: break-all;
    }
    #fileInfo .fileinfo-url a:hover {
        color: #ce1515;
    }
    #managerContainer {
        position: relative;
        height: 100%;
    }
    #folderContent, #managerActions {
        margin-right: 25%;
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }
    #folderContent {
        height: 100%;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        padding-top: 82px;
        min-height: 350px;
        overflow: auto;
        margin-top: -82px;
        position: relative;
    }
    #folderContent .content {
        position: relative;
        z-index: 2;
    }
    #folderContent .folder-background {
        position: absolute;
        height: 100%;
        width: 100%;
        top: 0;
        left: 0;
        z-index: 1;
    }
    .item-list-view {
        display: none;
    }
    #folderContent .item {
        width: 100px;
        float: left;
        text-align: center;
        margin: 12px;
        padding: 3px;
        border: 1px solid transparent;
        cursor: pointer;
    }
    #folderContent .item:hover, #folderContent .item.selected {
        background: #C6E0F3;
        border: 1px solid #69AFE2;
    }
    #folderContent .item.post-selected {
        border: 1px solid #69AFE2;
        background: transparent;
    }
    #folderContent .item .item-file-icon {
        width: 50px;
        height: 50px;
        margin: 10px auto;
        display: none;
    }
    .fileicon {
        width: 50px;
        height: 50px;
        background: url(/Content/images/file_type_icons.png) no-repeat;
    }
    .fileicon-folder {
        background-position: -229px -511px;
    }
    .fileicon-jpeg {
        background-position: -454px -395px;
    }
    .fileicon-gif {
        background-position: -5px -339px;
    }
    .fileicon-png {
        background-position: -341px -339px;
    }
    .fileicon-tiff {
        background-position: -61px -283px;
    }
    .fileicon-bmp {
        background-position: -285px -339px;
    }
    .fileicon-file {
        background-position: -454px -395px;
    }
    #folderContent .item .item-file-thumb {
        width: 50px;
        height: 50px;
        margin: 10px auto;
        position: relative;
    }
    #folderContent .item .item-file-thumb img {
        max-width: 50px;
        max-height: 50px;
        display: block;
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }
    #folderContent .item-file-name {
        -ms-word-break: break-all;
        word-break: break-all;
        font-size: 12px;
        overflow: hidden;
        line-height: 14px;
        height: 42px;
    }
    #managerActions {
        padding: 0 15px;
        height: 32px;
        border-bottom: 1px solid #ddd;
        background: #eee;
        position: relative;
        z-index: 10;
    }
    #managerActions input {
        display: inline-block;
        width: 32px;
        height: 32px;
        border: 0;
        cursor: pointer;
        outline: none;
        background: url(/Content/images/image_manager_icons.png) no-repeat;
    }
    #managerActions .seperator {
        height: 26px;
        width: 0;
        border-left: 1px solid #ccc;
        margin-bottom:4px;
        display: inline-block;
        margin-left: 5px;
        margin-right: 5px;
    }
    #managerActions input.btn-refresh {
        background-position: -288px 0;
    }
    #managerActions input.btn-parent {
        background-position: -32px 2px;
    }
    #managerActions input.btn-newdir {
        background-position: -64px 2px;
    }
    #managerActions input.btn-removedir {
        background-position: -96px 2px;
    }
    #managerActions input.btn-upload {
        background-position: -128px 2px;
    }
    #managerActions input.btn-download {
        background-position: -160px 2px;
    }
    #managerActions input.btn-remove {
        background-position: -192px 2px;
    }
    #managerActions input:hover {
        background-color: #ccc;
    }
    #managerActions input.disabled {
        -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         opacity: 0.4;
         cursor: default!important;
         background-color: transparent!important;
    }
    #managerActions input#imageUpload, #managerActions form {
        height: 0;
        width: 0;
        overflow: hidden;
    }
</style>
<script>
    var continueIfMarkerSet = true;
    var isItemSelected = false;
    var folderPath = "";
    var selectedPath = "";
    $(document).ready(function () {
        listFolderContent(folderPath);
    });
    $("#folderContent .folder-background").click(function () {
        isItemSelected = false;
        $("#folderContent .item.selected").removeClass("selected").addClass("post-selected");
        $("#btnUploadImage").removeClass("disabled");
        $("#btnDownloadImage").addClass("disabled");
        $("#btnRemoveImage").addClass("disabled");
        $("#btnNewDirectory").removeClass("disabled");
        $("#btnRemoveDirectory").addClass("disabled");
        selectedPath = "";
    });
    $("#btnRemoveImage").on("click", function () {
        if (!$(this).hasClass("disabled") && selectedPath != "") {
            deleteImageFromFolder(selectedPath);
        }
    });
    $("#btnDownloadImage").on("click", function () {
        if (!$(this).hasClass("disabled")) {
            window.open($("#folderContent .item.selected").attr("data-url"));
        }
    });
    $("#btnUploadImage").on("click", function () {
        if (!$(this).hasClass("disabled")) {
            $("#imageUpload").trigger("click");
        }
    });
    $("#btnRefresh").on("click", function () {
        if (!$(this).hasClass("disabled")) {
            saveFolderContentView(folderPath);
            listFolderContent(folderPath);
        }
    });
    $("#btnNewDirectory").on("click", function () {
        if (!$(this).hasClass("disabled")) {
            var newFolder = prompt("Please enter folder name.", "New Folder");
            if (newFolder != null) {
                if (newFolder == "Thumb") {
                    alert("This is a reserved name.");
                } else {
                    if (folderPath != "") {
                        newFolder = folderPath + "/" + newFolder;
                    }
                    createFolder(newFolder);
                }
            }
        }
    });
    $("#btnRemoveDirectory").on("click", function () {
        if (!$(this).hasClass("disabled") && selectedPath != "" && selectedPath != "/" && $("#folderContent .item.selected").length && $("#folderContent .item.selected").hasClass("folder") && $("#folderContent .item.selected").attr("data-location") == selectedPath) {
            var r = confirm("Are you sure you want to remove this folder and all its content?");
            if (r == true) {
                removeFolder(selectedPath);
            }
        }
    });
    $("#imageUpload").on("change", function () {
        var file = $('input[type=file]#imageUpload')[0].files[0];
        if (typeof file != "undefined") {
            if (file.size <= 1048576) {
                if (file.type == "image/pjpeg" || file.type == "image/jpeg" || file.type == "image/png" || file.type == "image/gif" || file.type == "image/tiff" || file.type == "image/bmp") {
                    uploadImageToFolder();
                } else {
                    alert("It is not a valid image file.");
                }
            } else {
                alert("File size cannot be larger than 1 MB.");
            }
            $(this).replaceWith($("#imageUpload").clone(true));
        }
    });
    $("#folderContent .item").live("click", function () {
        displayFileInfo($(this));
    });
    function uploadImageToFolder() {
        var formData = new FormData();
        formData.append('image', $('input[type=file]#imageUpload')[0].files[0]);
        $("#btnRefresh").addClass("disabled");
        $.ajax({
            url: '@Url.Action("UploadImageToFolder", "BlobPictureManager")',
            data: formData,
            contentType: false,
            processData: false,
            type: "POST"
        }).done(function (data) {
            if (data.success == true && typeof data.file != "undefined") {
                parseFile(data.file);
            }
            $("#btnRefresh").removeClass("disabled");
        }).error(function () {
            alert("Error occured!");
            $("#btnRefresh").removeClass("disabled");
        });
    }
    function deleteImageFromFolder(path) {
        if (typeof path != "undefined" && path != "") {
            $("#btnRefresh").addClass("disabled");
            $.ajax({
                url: '@Url.Action("DeleteImageFromFolder", "BlobPictureManager")',
                data: { path: path },
                type: "POST"
            }).done(function (data) {
                $("#folderContent .item[data-location='" + path + "']").remove();
                clearFileInfo();
                isItemSelected = false;
                $("#folderContent .item.selected").removeClass("selected").addClass("post-selected");
                $("#btnUploadImage").removeClass("disabled");
                $("#btnDownloadImage").addClass("disabled");
                $("#btnRemoveImage").addClass("disabled");
                $("#btnNewDirectory").removeClass("disabled");
                $("#btnRemoveDirectory").addClass("disabled");
                selectedPath = "";
                $("#btnRefresh").removeClass("disabled");
            }).error(function () {
                alert("Error occured!");
                $("#btnRefresh").removeClass("disabled");
            });
        }
    }
    function createFolder(path) {
        if (typeof path != "undefined" && path != "") {
            $.ajax({
                url: '@Url.Action("CreateFolder", "BlobPictureManager")',
                data: { path: path },
                type: "POST"
            }).done(function (data) {
                if (data.folder) {
                    parseFile(data.folder);
                }
            }).error(function () {
                alert("Error occured!");
            });
        }
    }
    function removeFolder(path) {
        if (typeof path != "undefined" && path != "") {
            $.ajax({
                url: '@Url.Action("RemoveFolder", "BlobPictureManager")',
                data: { path: path },
                type: "POST"
            }).done(function (data) {
                $("#folderContent .item[data-location='" + path + "']").remove();
                clearFileInfo();
            }).error(function () {
                alert("Error occured!");
            });
        }
    }
    function listFolderContent(folderName, marker) {
        $("#btnRefresh").addClass("disabled");
        if (typeof folderName === "undefined") {
            folderName = "";
        }
        if (typeof marker === "undefined") {
            marker = "";
        }
        $.ajax({
            url: "@Url.Action("ListFolderContent", "BlobPictureManager")",
            type: "POST",
            dataType: "JSON",
            data: { folder: folderName, marker: marker }
        }).done(function (data) {
            if (data.folderContent && data.count > 0) {
                for (var c in data.folderContent) {
                    parseFile(data.folderContent[c]);
                }
            }
            if (continueIfMarkerSet && typeof data.marker != "undefined" && data.marker != null && data.marker != "") {
                listFolderContent(folderName, data.marker);
            }
            if (data.marker == null || data.marker == "") {
                var folderList = $("#folderContent .item.folder").get();
                var fileList = $("#folderContent .item.file").get();
                folderList.sort(sortFilesByName);
                fileList.sort(sortFilesByName);
                for (var i = 0; i < folderList.length; i++) {
                    folderList[i].parentNode.appendChild(folderList[i]);
                }
                for (var i = 0; i < fileList.length; i++) {
                    fileList[i].parentNode.appendChild(fileList[i]);
                }
                $("#btnRefresh").removeClass("disabled");
            }
            if (data.count == 0 && !$("#folderContent .content .item").length) {
                $("#folderContent .content").html("<div>Folder is empty.</div>");
            }
        }).error(function () {
            $("#directoryTree .content, #folderContent .content").html("Request cannot be completed.");
        });
    }
    function saveFolderContentView(folderPath) {
        if (typeof folderPath == "undefined" || folderPath == "" || folderPath == null)
            folderPath = "/";
        $("#savedFolderContent > .savedfolder[data-path='" + folderPath + "']").remove();
        var savedFolders = $("#savedFolderContent > .savedfolder");
        if (savedFolders.length >= 10) {
            savedFolders.eq(0).remove();
        }
        $("#savedFolderContent").append('<div class="savedfolder" data-path="' + folderPath + '">' + $("#folderContent .content").html() + '</div>');
        $("#folderContent .content").empty();
    }
    function getSavedFolderContentView(folderPath) {
        if (typeof folderPath == "undefined" || folderPath == "" || folderPath == null)
            folderPath = "/";
        if ($("#savedFolderContent > .savedfolder[data-path='" + folderPath + "']").length) {
            $("#folderContent .content").empty().append($("#savedFolderContent > .savedfolder[data-path='" + folderPath + "']").html());
            return true;
        }
        return false;
    }
    function parseFile(file) {
        var typeIcon = "";
        var typeName = "";
        var fileIcon = "";
        var className = "file";
        var updated = "";
        var fileSize = "";
        var fileDimension = "";
        var thumbPath = "";
        var filePath = "";
        if (typeof file.LastModified != "undefined" && file.LastModified != null && file.LastModified != "") {
            updated = file.LastModified;
        }
        if (typeof file.Size != "undefined" && file.Size != null && file.Size != "") {
            fileSize = file.Size;
        }
        if (typeof file.Dimension != "undefined" && file.Dimension != null && file.Dimension != "") {
            fileDimension = file.Dimension;
        }
        if (typeof file.ThumbPath != "undefined" && file.ThumbPath != null && file.ThumbPath != "") {
            thumbPath = "<img src='" + file.ThumbPath + "' />";
        }
        if (typeof file.Path != "undefined" && file.Path != null && file.Path != "") {
            filePath = file.Path;
        }
        switch (file.Type) {
            case "folder":
                typeIcon = '<i class="fa fa-folder-o"></i>';
                typeName = "Folder";
                className = "folder";
                fileIcon = "<div class='fileicon fileicon-folder'></div>";
                thumbPath = fileIcon;
                break;
            case "image/pjpeg":
            case "image/jpeg":
                typeIcon = '<i class="fa fa-file-image-o"></i>';
                typeName = "JPEG Image";
                fileIcon = "<div class='fileicon fileicon-jpeg'></div>";
                break;
            case "image/png":
                typeIcon = '<i class="fa fa-file-image-o"></i>';
                typeName = "PNG Image";
                fileIcon = "<div class='fileicon fileicon-png'></div>";
                break;
            case "image/gif":
                typeIcon = '<i class="fa fa-file-image-o"></i>';
                typeName = "GIF Image";
                fileIcon = "<div class='fileicon fileicon-gif'></div>";
                break;
            case "image/tiff":
                typeIcon = '<i class="fa fa-file-image-o"></i>';
                typeName = "TIFF Image";
                fileIcon = "<div class='fileicon fileicon-tiff'></div>";
                break;
            case "image/bmp":
                typeIcon = '<i class="fa fa-file-image-o"></i>';
                typeName = "BMP Image";
                fileIcon = "<div class='fileicon fileicon-bmp'></div>";
                break;
            default:
                if (file.Name.endsWith(".gif")) {
                    typeIcon = '<i class="fa fa-file-image-o"></i>';
                    typeName = "GIF Image";
                    fileIcon = "<div class='fileicon fileicon-gif'></div>";
                } else if (file.Name.endsWith(".png")) {
                    typeIcon = '<i class="fa fa-file-image-o"></i>';
                    typeName = "PNG Image";
                    fileIcon = "<div class='fileicon fileicon-png'></div>";
                } else if (file.Name.endsWith(".bmp")) {
                    typeIcon = '<i class="fa fa-file-image-o"></i>';
                    typeName = "BMP Image";
                    fileIcon = "<div class='fileicon fileicon-bmp'></div>";
                } else if (file.Name.endsWith(".tif") || file.Name.endsWith(".tiff")) {
                    typeIcon = '<i class="fa fa-file-image-o"></i>';
                    typeName = "TIFF Image";
                    fileIcon = "<div class='fileicon fileicon-tiff'></div>";
                } else if (file.Name.endsWith(".jpg") || file.Name.endsWith(".jpeg") || file.Name.endsWith(".jpe") || file.Name.endsWith(".jfif") || file.Name.endsWith(".pjpeg") || file.Name.endsWith(".pjp")) {
                    typeIcon = '<i class="fa fa-file-image-o"></i>';
                    typeName = "JPEG Image";
                    fileIcon = "<div class='fileicon fileicon-jpeg'></div>";
                } else {
                    typeIcon = '<i class="fa fa-file-o"></i>';
                    typeName = "File";
                    fileIcon = "<div class='fileicon fileicon-file'></div>";
                }
                break;
        }
        $("#folderContent .content").append("<div class='item " + className + "' data-name='" + file.Name + "' data-location='" + file.Location + "' data-url='" + filePath + "' data-type='" + typeName + "' data-updated='" + updated + "' data-dimension='" + fileDimension + "' data-size='" + fileSize + "'>" +
            "<div class='item-list-view'><div class='item-list-icon'>" + typeIcon + "</div><div class='item-list-name'>" + file.Name + "</div><div class='item-list-type'>" + typeName + "</div><div class='item-list-updated'>" + updated + "</div><div class='item-list-dimension'>" + fileDimension + "</div><div class='item-list-size'>" + fileSize + "</div></div>" +
            "<div class='item-file-view'><div class='item-file-icon'>" + fileIcon + "</div><div class='item-file-thumb'>" + thumbPath + "</div><div class='item-file-name'>" + file.Name + "</div></div></div>");

    }
    function displayFileInfo(file) {
        // Bypass deselect when clicking anywhere on page
        isItemSelected = true;
        if (file.hasClass("file")) {
            clearFileInfo();
            file.addClass("selected");

            $("#fileInfo .content").empty();
            $("#fileInfo .content").append('<div class="fileinfo-thumb"><img src="' + file.attr("data-url") + '"></div>');
            $("#fileInfo .content").append('<div class="fileinfo-name">' + file.find(".item-list-name").html() + '</div>');
            $("#fileInfo .content").append('<div class="fileinfo-dimension">' + file.attr("data-dimension") + '</div>');
            $("#fileInfo .content").append('<div class="fileinfo-size">' + file.attr("data-size") + '</div>');
            $("#fileInfo .content").append('<div class="fileinfo-type">' + file.attr("data-type") + '</div>');
            $("#fileInfo .content").append('<div class="fileinfo-updated">Last updated ' + file.attr("data-updated") + '</div>');
            $("#fileInfo .content").append('<div class="fileinfo-url"><a href="' + file.attr("data-url") + '" target="_blank">' + file.attr("data-url") + '</a></div>');
            selectedPath = file.attr("data-location");
            $("#btnUploadImage").addClass("disabled");
            $("#btnDownloadImage").removeClass("disabled");
            $("#btnRemoveImage").removeClass("disabled");
            $("#btnNewDirectory").addClass("disabled");
            $("#btnRemoveDirectory").addClass("disabled");
        } else if (file.hasClass("folder")) {
            clearFileInfo();
            file.addClass("selected");
            $("#fileInfo .content").empty();
            $("#fileInfo .content").append('<div class="fileinfo-icon">' + file.find(".item-file-icon").html() + '</div>');
            $("#fileInfo .content").append('<div class="fileinfo-name">' + file.find(".item-list-name").html() + '</div>');
            $("#fileInfo .content").append('<div class="fileinfo-type">' + file.attr("data-type") + '</div>');
            selectedPath = file.attr("data-location");
            $("#btnUploadImage").removeClass("disabled");
            $("#btnDownloadImage").addClass("disabled");
            $("#btnRemoveImage").addClass("disabled");
            $("#btnNewDirectory").removeClass("disabled");
            $("#btnRemoveDirectory").removeClass("disabled");
        }
    }
    function clearFileInfo() {
        $("#folderContent .item").removeClass("selected post-selected");
        $("#fileInfo .content").text("No file selected.");
    }
    function sortFilesByName(a, b) {
        var sa = a.getAttribute("data-name").toLowerCase(), sb = b.getAttribute("data-name").toLowerCase();
        return sb < sa ? -1 : sb > sa ? 1 : 0;
    }
    if (typeof String.prototype.endsWith !== 'function') {
        String.prototype.endsWith = function (suffix) {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        };
    }
</script>